package com.devin.dao;

import com.devin.pojo.Member;
import com.devin.pojo.Order;
import com.devin.pojo.Product;
import com.devin.pojo.Traveller;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.cache.decorators.LruCache;
import org.apache.ibatis.mapping.FetchType;
import org.omg.PortableInterceptor.INACTIVE;

import java.util.List;

@Mapper
@CacheNamespace(blocking = true,eviction = LruCache.class,flushInterval = 0L,size=1024,readWrite = true)
public interface OrderMapper {
    @Select(" select * from orders")
    @Results({@Result(id = true,property = "id",column = "id")
            ,@Result(property = "product",column = "productId",javaType = Product.class,one = @One(select= "com.devin.dao.ProductMapper.getProductById",fetchType = FetchType.EAGER))
    })
    @Options(useCache = true)
    List<Order> getOrders(Integer page,Integer size);

    @Insert("insert into member values(null,#{name},#{nickName},#{phoneNum},#{email})")
    @Options(useGeneratedKeys = true,keyProperty = "id",keyColumn = "id")
    void addMember(Member member);

    @Insert("insert into orders values(null,replace(UUID(),'-',''),#{orderTime},#{peopleCount},#{orderDesc},#{payType},#{orderStatus},#{productId},#{memberId})")
    @Options(useGeneratedKeys = true,keyColumn = "id",keyProperty = "id")
    void addOrder(Order order);

    @Select("select * from orders where id=#{orderId}")
    @Results({@Result(id = true,property = "id",column = "id")
            ,@Result(property = "product",column = "productId",javaType = Product.class,one=@One(select="com.devin.dao.ProductMapper.getProductById",fetchType = FetchType.EAGER))
            ,@Result(property = "travellers",column = "id",javaType = List.class,many = @Many(select = "com.devin.dao.OrderMapper.getTravellers",fetchType = FetchType.EAGER))
            ,@Result(property = "member",column = "memberId",javaType = Member.class,one=@One(select = "com.devin.dao.OrderMapper.getMember",fetchType = FetchType.EAGER))
    })
    @Options(useCache = true)
    Order getOrderInfo(Integer orderId);

    @Select("select * from traveller where id in (select travellerid from order_traveller where orderid=#{orderId})")
    @Options(useCache = true)
    List<Traveller> getTravellers(Integer orderId);

    @Select("select * from member where id=#{memberId}")
    @Options(useCache = true)
    Member getMember(Integer memberId);

    @Delete("delete from member where id=#{memberId}")
    void delMember(Integer memberId);

    @Delete("delete from order_traveller where orderid=#{orderId}")
    void delOrderAndTravellers(Integer orderId);

    @Delete("delete from traveller where id in (select travellerid from order_traveller where orderid=#{orderId})")
    void delTravellers(Integer orderId);

    @Delete("delete from orders where id=#{orderId}")
    void delOrder(Integer orderId);
}